-- UIMailDetail
-- Created by cheny3
-- 邮件详细内容界面

UIMailDetail = class("UIMailDetail", function()
    return cc.Layer:create();
end);

-- 传入奖励列表
function UIMailDetail.create(title, bonus, okFunc, msg, okText, extraPara)
    return UIMailDetail.new(title, bonus, okFunc, msg, okText, extraPara);
end

-- 每次最多可显示的奖励个数
local MAX_BONUS_COUNT = 6;
-- 两侧对齐文本修正位置参数
local LABEL_WIDTH = 490;
-- 底纹印花修正位置
local IMG_POX = 281;

-- 需要修正高度的物品集合
local needFixPosYItems = {};

-- 构造函数
function UIMailDetail:ctor(title, bonus, okFunc, msg, okText, extraPara)
    self:setName("UIMailDetail");
    local node = cc.CSLoader:createNode("layout/common/BonusNotify3.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.BONUS_NOTIFY_ZORDER + 1);

    -- 先把bonus的数据深拷贝出来，因为后面有可能会修改bonus数据
    bonus = table.deepcopy(bonus);
    -- 对奖励进行排序
    if not extraPara or not extraPara.noSortBonus then
        bonus = self:sortBonus(bonus);
    end

    -- 相关参数
    self.title = title
    self.bonus = bonus;
    self.okFunc = okFunc;
    self.msg = msg;
    self.okText = okText;
    self.extraPara = extraPara;

    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UIMailDetail 界面析构清理");
            if type(self.exitFunc) == "function" then
                self.exitFunc();
                self.exitFunc = nil;
            end
        end
    end)

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 对奖励进行排序
function UIMailDetail:sortBonus(bonus)
    -- 按照奖励类型排序，物品在前，属性在后
    table.sort(bonus, function(a, b) return a[1] < b[1]; end);
    return bonus;
end

-- 重绘
function UIMailDetail:redraw()
    -- 设置标题
    local titleNode = findChildByName(self.node, "CT/title_node");
    local titleLabel = findChildByName(titleNode, "title");
    local title = getLocStr("achive_award");
    if type(self.title) == "string" and string.len(self.title) > 0 then
        title = self.title;
    end
    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(title);

    -- 设置副标题
    if self.extraPara then
        local timeDesc = self.extraPara["timeDesc"];
        if type(timeDesc) == "string" and string.len(timeDesc) > 0 then
            local subTitle = findChildByName(titleNode, "sub_title");
            TextStyleM.setTextStyle(subTitle, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE);
            subTitle:setString(timeDesc);
        end
    end

    -- 正文样式
    local descLabel = findChildByName(self.node, "CT/desc");
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);

    if type(self.msg) == "string" and string.len(self.msg) > 0 then
        -- 先解析一下左右对齐参数
        local alignMsg = getMsgAlignmentTag(self.msg);
        local alignTag = alignMsg[2];
        if alignTag == "left" then
            -- 左对齐
            self.msg = alignMsg[1];
            descLabel:getVirtualRenderer():setHorizontalAlignment(cc.TEXT_ALIGNMENT_LEFT);
            descLabel:setAnchorPoint(0, 1);
            descLabel:setPositionX(-LABEL_WIDTH / 2);
        elseif alignTag == "right" then
            -- 右对齐
            self.msg = alignMsg[1];
            descLabel:getVirtualRenderer():setHorizontalAlignment(cc.TEXT_ALIGNMENT_RIGHT);
            descLabel:setAnchorPoint(1, 1);
            descLabel:setPositionX(LABEL_WIDTH / 2);
        end
        -- 默认居中不处理

        -- 使用传入的邮件内容
        descLabel = applyString(descLabel, self.msg);
    end

    -- 每次最多显示 MAX_BONUS_COUNT 个奖励，若超过该数量，需要分批显示
    local bonusCount;
    if #self.bonus <= MAX_BONUS_COUNT then
        local bonus = self.bonus;
        self:initBonusItem(bonus);
        self.bonus = {};
        bonusCount = #bonus;
    else
        -- 取出一批奖励进行显示
        local bonus = {};
        for i = 1, MAX_BONUS_COUNT do
            table.insert(bonus, self.bonus[1]);
            table.remove(self.bonus, 1);
        end
        self:initBonusItem(bonus);
        bonusCount = #bonus;
    end

    -- 自适应所有组件
    local bg = findChildByName(self.node, "CT/bg_frame");
    local bonusPanel = findChildByName(self.node, "CT/bonus_panel");
    local bonusPanel2 = findChildByName(self.node, "CT/bonus_panel2");
    local okBtn = findChildByName(self.node, "CT/btn_ok");
    local descLabel = findChildByName(self.node, "CT/desc");

    local nodeArr = { titleNode, descLabel, bonusPanel, okBtn};
    local offsetArr = { 100, };

    if bonusCount > 4 then
        nodeArr = { titleNode, descLabel, bonusPanel2, okBtn};
        offsetArr = {100, nil, 10};
    elseif bonusCount > 0 then
        nodeArr = { titleNode, descLabel, bonusPanel, okBtn};
    else
        nodeArr = { titleNode, descLabel, okBtn};
        bonusPanel:setVisible(false);
        bonusPanel2:setVisible(false);
    end

    AlignM.adaptLayout(bg, AlignM.BG_SIZE_NORMAL, nodeArr, offsetArr);
    AlignM.adaptSubBg(self.node, AlignM.BG_SIZE_NORMAL, bg:getScaleY());

    -- 根据适配后的界面高度比例，对界面上的角标位置进行修正
    local bg1 = findChildByName(self.node, "CT/sub_bg_l");
    local bg2 = findChildByName(self.node, "CT/sub_bg_r");

    -- 这里要注意一下，原始的模版高度并不是100%，而是85%。。不解
    local fixY, deltaY = math.modf(AlignM.BG_SIZE_NORMAL.height * (0.85 - bg:getScaleY()) / 2);

    if fixY > 0 then
        fixY = fixY + 20 * (bg:getScaleY() - 0.85);
    else
        fixY = fixY - 15 * (0.85 - bg:getScaleY());
    end

    -- 背景还原宽度
    bg:setScaleX(1);

    -- 修正底纹位置
    bg1:setPositionX(-IMG_POX);
    bg2:setPositionX(IMG_POX);
    bg1:setPositionY(bg1:getPositionY() - fixY);
    bg2:setPositionY(bg2:getPositionY() - fixY);
end

-- 注册点击事件
function UIMailDetail:registerTouchEvent()
    -- 确认按钮
    local okBtn = findChildByName(self.node, "CT/btn_ok");
    TextStyleM.setTextStyle(okBtn, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    okBtn:setTitleText(self.okText or getLocStr("confirm"));

    -- 确定按钮不可点击的处理
    if self.enable == false then
        -- 灰化按钮
        okBtn:setBright(false);
        okBtn:setTouchEnabled(false);
    end

    if self.needBackBtn == true then
        -- 显示返回按钮
        local btNode = findChildByName(self.node, "BT");
        btNode:setVisible(true);
        local btnBack = findChildByName(self.node, "BT/btn_back");
        TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
        btnBack:setTitleText(getLocStr("btn_text_back"));
    end

    local function onCloseClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");

            -- 奖励都显示完了
            if #self.bonus == 0 then
                if self.okFunc then
                    self.okFunc();
                    self.okFunc = nil;
                end
                -- 关闭当前界面
                UIMgr.getCurrentScene():removeFormByName("UIMailDetail");
            else
                -- 还有奖励没显示，继续
                self:redraw();
            end
        end
    end
    AddBackEventHandler(self, okBtn, onCloseClick);

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");

            UIMgr.getCurrentScene():removeFormByName("UIMailDetail");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
end

-- 初始化奖励
function UIMailDetail:initBonusItem(bonusList)
    local parentNode = findChildByName(self.node, "CT/bonus_panel/bonus_node");
    local parentNode2 = findChildByName(self.node, "CT/bonus_panel2/bonus_node");

    -- 先清空
    parentNode:removeAllChildren();
    parentNode2:removeAllChildren();

    local item = cc.CSLoader:createNode("layout/equip/equip_item.csb");
    item = replaceNodeWithWidget(item);

    local descLabel = findChildByName(self.node, "CT/desc");

    local itemWidth = 100;
    local gap = 20;
    local widget = ccui.Widget:create();
    local widget2 = ccui.Widget:create();
    local totalWidth = #bonusList * (itemWidth + gap);
    local totalWidth2 = #bonusList * (itemWidth + gap);
    local itemsStr = "";
    local totalCount = #bonusList;
    local msg = "";

    if totalCount == 4 then
        -- 四个修改间距
        gap = 3;
        totalWidth = #bonusList * (itemWidth + gap);
    elseif totalCount > 4 then
        -- 多行修正
        totalWidth = 3 * (itemWidth + gap);
        totalWidth2 = (totalCount - 3) * (itemWidth + gap);
    end

    for i = 1, totalCount do
        local bonus = bonusList[i];
        local child = item:clone();
        child:setPositionX((i - 1) * (itemWidth + gap));
        if totalCount ~= 4 and i >= 4 then
            -- 修正第二行的位置
            child:setPositionX((i - 1 - 3) * (itemWidth + gap));
            child:setPositionY(child:getPositionY() - 100);
        end

        -- 图标
        local name;
        local iconPath;
        local scale = 0.88;
        local offsetY = 0;
        local icon = findChildByName(child, "btn");
        local tip = getLocStr("get_res_tip");
        if bonus[1] == 1 then
            -- 是道具， 获取道具图标
            iconPath = getItemIconPath(ItemM.query(bonus[2], "icon"));
            name = ItemM.query(bonus[2], "name");

            if ItemM.query(bonus[2], "type") == ITEM_TYPE_SPELL then
                local itemBg = findChildByName(child, "bg");
                itemBg:setVisible(false);
            end

            -- 以下物品需要修正高度
            if table.indexOf(needFixPosYItems, bonus[2]) ~= -1 then
                offsetY = 5;
            end
        elseif bonus[1] == 2 then
            -- 属性
            iconPath = getLargeAttribIconPath(FieldsM.query(bonus[2], "icon"));
            name = FieldsM.query(bonus[2], "name");
            -- 不同属性提示不同
            if bonus[2] == "hp" or bonus[2] == "mp" then
                tip = getLocStr("get_res_tip_2");
            elseif table.indexOf({"max_hp", "max_mp", "attack", "magic", "dodge"}, bonus[2]) > 0 then
                tip = getLocStr("get_res_tip_1");
            else
                tip = getLocStr("get_res_tip");
            end
        elseif bonus[1] == 3 then
            -- 英雄
            local classId = tonumber(bonus[2]);
            local fileName = PetM.getDefaultIcon(classId);
            iconPath = getHeroIconPath(tostring(fileName));
            name = PetM.query(classId, "name");
            scale = 0.8;
            offsetY = 5;
        elseif bonus[1] == 6 then
            -- 飞艇秘宝
            local skillId = tonumber(bonus[2]);
            local fileName = SkyShipSkillM.query(skillId, "icon");
            iconPath = getAirShipSkillIconPath(tostring(fileName));
            name = SkyShipSkillM.query(skillId, "name");
        elseif bonus[1] == 8 then
            -- 机器人
            iconPath = getRobotIconPath(SkyRobotM.query(bonus[2], "icon"));
            name = SkyRobotM.query(bonus[2], "name");
        end
        icon:loadTexture(iconPath)
        icon:setScale(scale);
        icon:setPositionY(icon:getPositionY() + offsetY);

        icon:addTouchEventListener(function(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                showBonusDesc(bonus);
            end
        end);

        -- 个数
        local countLabel = findChildByName(child, "count");
        TextStyleM.setTextStyle(countLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -3);
        countLabel:setString(tostring(bonus[3]));
        countLabel:setVisible(true);
        countLabel:setPositionX(0);
        countLabel:setPositionY(-itemWidth/2 + 5);

        if i >= 4 and totalCount ~= 4 then
            widget2:addChild(child);
        else
            widget:addChild(child);
        end
    end

    widget:setPositionX(- totalWidth / 2 + (itemWidth + gap) / 2);
    widget2:setPositionX(- totalWidth2 / 2 + (itemWidth + gap) / 2);
    if totalCount > 4 then
        local bonusPanel2 = findChildByName(self.node, "CT/bonus_panel2");
        bonusPanel2:setVisible(true);
        parentNode2:addChild(widget);
        parentNode2:addChild(widget2);
    else
        local bonusPanel = findChildByName(self.node, "CT/bonus_panel");
        bonusPanel:setVisible(true);
        parentNode:addChild(widget);
    end
end

-- 适配
function UIMailDetail:resize()
    local node = self.node;

    -- bg充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

